package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.*;
import org.dromara.app.appReturn.AppDaRenInfo;
import org.dromara.app.appReturn.AppMemberCenterReturn;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkDaRenApplyBo;
import org.dromara.app.domain.vo.SkDaRenApplyVo;
import org.dromara.app.domain.SkDaRenApply;
import org.dromara.app.mapper.SkDaRenApplyMapper;
import org.dromara.app.service.ISkDaRenApplyService;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 达人申请信息Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkDaRenApplyServiceImpl implements ISkDaRenApplyService {

    private final SkDaRenApplyMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    @Value("${txyun.secret-id}")
    private  String secretId;

    @Value("${txyun.secretKey}")
    private  String secretKey;

    @Value("${txyun.faceduibi}")
    private  String faceduibi;

    /**
     * 查询达人申请信息
     *
     * @param id 主键
     * @return 达人申请信息
     */
    @Override
    public SkDaRenApplyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询达人申请信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 达人申请信息分页列表
     */
    @Override
    public TableDataInfo<SkDaRenApplyVo> queryPageList(SkDaRenApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkDaRenApply> lqw = buildQueryWrapper(bo);
        Page<SkDaRenApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的达人申请信息列表
     *
     * @param bo 查询条件
     * @return 达人申请信息列表
     */
    @Override
    public List<SkDaRenApplyVo> queryList(SkDaRenApplyBo bo) {
        LambdaQueryWrapper<SkDaRenApply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkDaRenApply> buildQueryWrapper(SkDaRenApplyBo bo) {
        Map<String, Object> params = bo.getParams();
        //判断是否城市代理账户
        LoginUser user = LoginHelper.getLoginUser();
        if (user.getRolePermission().contains("cityAgent")){
            //是城市代理人
            bo.setCity(user.getCity());
        }
        LambdaQueryWrapper<SkDaRenApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImage()), SkDaRenApply::getHeadImage, bo.getHeadImage());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), SkDaRenApply::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getHeight()), SkDaRenApply::getHeight, bo.getHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getWeight()), SkDaRenApply::getWeight, bo.getWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), SkDaRenApply::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), SkDaRenApply::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getWebchat()), SkDaRenApply::getWebchat, bo.getWebchat());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SkDaRenApply::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonalityTag()), SkDaRenApply::getPersonalityTag, bo.getPersonalityTag());
        lqw.eq(StringUtils.isNotBlank(bo.getAccompanyingType()), SkDaRenApply::getAccompanyingType, bo.getAccompanyingType());
        lqw.eq(StringUtils.isNotBlank(bo.getPhoto()), SkDaRenApply::getPhoto, bo.getPhoto());
        lqw.eq(StringUtils.isNotBlank(bo.getVideo()), SkDaRenApply::getVideo, bo.getVideo());
        lqw.eq(bo.getState() != null, SkDaRenApply::getState, bo.getState());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SkDaRenApply::getCity, bo.getCity());
        lqw.orderByDesc(SkDaRenApply::getCreateTime);
        return lqw;
    }

    /**
     * 新增达人申请信息
     *
     * @param bo 达人申请信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkDaRenApplyBo bo) {
        SkDaRenApply add = MapstructUtils.convert(bo, SkDaRenApply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改达人申请信息
     *
     * @param bo 达人申请信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkDaRenApplyBo bo) {
        SkDaRenApply update = MapstructUtils.convert(bo, SkDaRenApply.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkDaRenApply entity){
        //TODO 做一些数据校验,如唯一约束
        if (entity.getId()!=null && entity.getState().longValue()==1){ //同意审核成功
            SkAppUser appUser = BeanUtil.copyProperties(entity,SkAppUser.class);
            appUser.setUserType(2L);
            skAppUserMapper.update(appUser,new QueryWrapper<SkAppUser>().lambda().eq(SkAppUser::getId,entity.getUserId()));
        }
    }

    /**
     * 校验并批量删除达人申请信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 甄选达人信息
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppDaRenInfo> getSelectedOutfits(AppTuiJianParams params, HttpServletRequest req) {
        List<AppDaRenInfo> list = baseMapper.getSelectedOutfits(params);
        return list;
    }

    /**
     * 达人申请
     */
    @Override
    public void daRenApplication(AppDaRenParams params, HttpServletRequest req) throws TencentCloudSDKException {
        Long userId = CssUtils.getUserId(req);
        List<SkDaRenApply> list = baseMapper.selectList(
            new QueryWrapper<SkDaRenApply>().lambda()
                .eq(SkDaRenApply::getUserId,userId)
                .ne(SkDaRenApply::getState,2)
        );
        if (list.size()>0){
            CssExceptionDescription.errorMsg(10011);
        }
        SkDaRenApply skDaRenApply = BeanUtil.copyProperties(params,SkDaRenApply.class);
        skDaRenApply.setUserId(userId);
        //人脸对比
        int faceNumber = CssUtils.faaceDuiBi(faceduibi,secretId,secretKey,skDaRenApply.getVideo(),skDaRenApply.getPhoto().split(",")[0]);
        if (faceNumber < 0) {
            //小于60需要后台审核
            skDaRenApply.setState(0L);
        }else{
            skDaRenApply.setState(1L);
            //大于60自动审核
            SkAppUser appUser = BeanUtil.copyProperties(skDaRenApply,SkAppUser.class);
            appUser.setUserType(2L);
            skAppUserMapper.update(appUser,new QueryWrapper<SkAppUser>().lambda().eq(SkAppUser::getId,skDaRenApply.getUserId()));
        }
        baseMapper.insert(skDaRenApply);
    }

    /**
     * 甄选搭子列表
     */
    @Override
    public List<AppDaRenInfo> getSelectionSubItemsList(AppPageParams params, HttpServletRequest req) {
        List<AppDaRenInfo> list = baseMapper.getSelectionSubItemsList(params);
        if (list.size() > 0) {
            for(AppDaRenInfo app:list){
                if (app.getBirthday() != null && !app.getBirthday().equals("")) {
                    if(isValidYearMonth(app.getBirthday())){
                        LocalDate bir = LocalDate.parse(app.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        Period age = Period.between(bir, LocalDate.now());
                        if (age.getYears()<0){
                            app.setAge("0");
                        }else{
                            app.setAge(age.getYears() + "");
                        }

                    }else{
                        app.setAge("0");
                    }
                }
                if (app.getVipTime() != null) {
                    //判断是否是会员
                    if (app.getVipType().longValue() > 0) {
                        if (app.getVipTime().getTime() < new Date().getTime()) {
                            app.setVipType(0L);
                        }
                    }
                } else {
                    app.setVipType(0L);
                }
            }
        }
        return list;
    }

    /**
     * 时间判断
     */
    public static boolean isValidYearMonth(String text) {
        // 定义年月的正则表达式
        String regex = "^\\d{4}-\\d{2}$";
        // 检查文本是否匹配正则表达式
        if (text.matches(regex)) {
            try {
                // 使用DateTimeFormatter解析字符串
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
                formatter.parse(text);
                System.out.println("true");
                // 如果没有异常抛出，说明是有效的年月格式
                return true;
            } catch (Exception e) {
                // 字符串不是有效的日期
                System.out.println("false");
                return false;
            }
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate localDate = LocalDate.parse("2024-04", formatter);
        System.out.println(localDate);
    }

}
